package logic

import (
	"context"
	"fmt"
	"wechat/model/cache"
	"wechat/model/mysql"

	"wechat/wechatrpc/internal/svc"
	"wechat/wechatrpc/wechatrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *wechatrpc.LoginRequest) (*wechatrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.User
	mysql.DB.Where("account=?", in.Account).Find(&user)

	if user.ID == 0 {
		return nil, fmt.Errorf("用户不存在,请重新输入")
	}

	if user.Password != in.Password {
		return nil, fmt.Errorf("密码输入错误,请重新输入")
	}

	SendSmsCount, _ := cache.Rdb.Get(l.ctx, "SendSmsKey"+in.Account).Result()
	if in.SendSms != SendSmsCount {
		return nil, fmt.Errorf("短信验证码,请重新输入")
	}
	return &wechatrpc.LoginResponse{
		UserId: int64(user.ID),
	}, nil
}
